//
//  DownloadManager.swift
//  TestBankActor
//
//  Created by 罗万能 on 2025/6/17.
//

import Foundation
import SwiftData

class DownloadManager: NSObject,URLSessionDownloadDelegate{
    var session: URLSession
    var downloadTask: URLSessionDownloadTask?
    var actor: BeautyModelActor
    var model: BeautyModel
    
    
    init(model: BeautyModel,actor: BeautyModelActor){
        self.actor = actor
        self.model = model
        let config = URLSessionConfiguration.background(withIdentifier: "com.testbankactor.download.\(model.id)")
        self.session = URLSession(configuration: config, delegate: nil, delegateQueue: OperationQueue())
        super.init()
        self.session =  URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
    }
    
    var localFolder: URL{
        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("Download")
        if !FileManager.default.fileExists(atPath: url.path) {
            try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
        }
        return url
    }
    
    func startDownload() async {
        Task.detached{
            let resumeData = await self.actor.getResumeData(model: self.model)
            let status = await self.actor.getStaus(model: self.model)
            if   resumeData != nil {
                self.downloadTask = self.session.downloadTask(withResumeData: resumeData!)
                
            }else if resumeData == nil  ,  status == .notStart {
                self.downloadTask = self.session.downloadTask(with: URLRequest(url: await self.actor.getRemoteUrl(model: self.model)))
            }
            self.downloadTask?.delegate = self
            self.downloadTask?.resume()
        }
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        Task{
            let fileName = downloadTask.response?.suggestedFilename ?? "\( model.id.uuidString).mp4"
            let destinationURL = localFolder.appendingPathComponent(fileName)
            do {
                if FileManager.default.fileExists(atPath: destinationURL.path) {
                    try FileManager.default.removeItem(at: destinationURL)
                }
                try FileManager.default.moveItem(at: location, to: destinationURL)
                 await actor.completeDownload(model: model,with: destinationURL)
            } catch {
               await actor.changeStatus(model: model, to:  .failed(errorMsg: error.localizedDescription))
            }
        }
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        guard totalBytesExpectedToWrite > 0 else { return }
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        Task { await actor.changeStatus(model: model   , to: .downloading(progress: progress)) }
    }
    
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error {
            Task { await actor.changeStatus(model: model, to: .failed(errorMsg: error.localizedDescription)) }
        }
    }
    
}
